package com.zhiwang.planet.ui.jsmodule

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Environment
import android.view.LayoutInflater
import android.webkit.JavascriptInterface
import android.webkit.WebView
import androidx.appcompat.app.AlertDialog
import androidx.core.content.contentValuesOf
import com.planet.processor.JsModule
import com.zhiwang.planet.R
import com.zhiwang.planet.di.component.DaggerUtilComponent
import com.zhiwang.planet.download.filedownloader.FileDownLoadManager
import com.zhiwang.planet.event.AppDownLoadProgressEvent
import com.zhiwang.planet.mvp.p.SdkPresenter
import com.zhiwang.planet.mvvm.model.entity.main.ServiceQQ
import com.zhiwang.planet.service.GameApkDownLoadService
import com.zhiwang.planet.ui.BaseActivity
import com.zhiwang.planet.ui.LoginActivity
import com.zhiwang.planet.ui.common.NodeCoordinate
import com.zhiwang.planet.ui.common.PhotoPreviewActivity
import com.zhiwang.planet.util.*
import kotlinx.android.synthetic.main.qq_copy_dialog_layout.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

@JsModule
class CommonModule constructor(context: BaseActivity,var webView:WebView?) : BaseJsModule(context) {


    private var appName:String = ""

    @Inject
    lateinit var sdkPresenter:SdkPresenter

    init {
        EventBus.getDefault().register(this)
        DaggerUtilComponent.builder()
                .appComponent(context.getAppComponent())
                .build()
                .inject(this)
    }

    /**
     * [l] 距离屏幕左边的像素距离
     * [t] 距离webview顶部距离
     */
    @JavascriptInterface
    fun showPhotoView(url: String/*, l: String, t: String, w: String, h: String*/) {
        val left = "1".toInt()
        val top = "1".toInt()
        val width = "2".toInt()
        val height = "2".toInt()
        val nodeCoordinate = NodeCoordinate(left = left, top = top, width = width, height = height)
        PhotoPreviewActivity.load(this, url, nodeCoordinate)
    }

    @JavascriptInterface
    fun download(url: String) {
        Toaster.message(url)
    }

    /**
     * 复制到剪切板
     */
    @JavascriptInterface
    fun copyToClipBoard(text: String) {
        copy(text)

        Toaster.message("已复制到剪切板")

    }

    @JavascriptInterface
    fun launchApp(packageName: String) {
        val intentForPackage = packageManager.getLaunchIntentForPackage(packageName)
        if (intentForPackage == null)
//            Toasty.message("未找到安装应用$packageName")
        else {
            intentForPackage.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intentForPackage)
        }
    }

    @JavascriptInterface
    fun setAppName(appName: String) {
        this.appName = appName
        //如果此时正在下载
        val progress = GameApkDownLoadService.getAppDownloadProgress(appName)
        if (progress.isNotEmpty())
            context.runOnUiThread {
                webView?.loadUrl("javascript:downloadGame(\'$progress\',\'$appName\')")
            }
    }

    @JavascriptInterface
    fun downloadAPP(url: String) {

        FileDownLoadManager.download(url, appName,
                getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath
                        ?: Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath)
    }

    @JavascriptInterface
    fun downloadAPP(url: String,appName:String) {

        this.appName = appName
        FileDownLoadManager.download(url, appName,
                getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath
                        ?: Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath)
    }

    @JavascriptInterface
    fun isAppInstalled(packageName: String): String {
        var installed = "false"
        try {
            packageManager.getPackageInfo(packageName, 0)
            installed = "true"
        } catch (e: PackageManager.NameNotFoundException) {
//            Log.i(TAG, "应用未安装")
//            Toasty.message("未安装应用$packageName")
        }
//        Toasty.message(installed)
        return installed
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAppDownloadProgress(event: AppDownLoadProgressEvent) {
        webView?.loadUrl("javascript:downloadGame(\'${event.progress}\',\'${event.name}\')")
    }

    @JavascriptInterface
    fun getAppDownloadProgress(appName: String): String {
        return GameApkDownLoadService.getAppDownloadProgress(appName)
    }

    @JavascriptInterface
    fun requestLogin() {
        TokenManager.clearToken()
        context.onAuthExpired()
        context.suicideAfterTransition()
    }

    @JavascriptInterface
    fun close() {
        context.suicideAfterTransition()
    }


    @JavascriptInterface
    fun getDeviceId():String{
       return TokenManager.getDeviceId()
    }

    @JavascriptInterface
    fun contactService(){

        sdkPresenter.getServiceQQ({

            if (it.userFullUri) {
                Utils.open(context, it.fullUri)
            } else {

                when {
                    it.showDialog -> showQQCopyDialog(it)

                    it.type == 0 -> Utils.joinQQGroup(context, it.groupKey)

                    else -> Utils.addFriend(context, it.singleQQ)

                }
            }

        }, context::onError)
    }


    private fun showQQCopyDialog(serviceQQ: ServiceQQ) {

        val view = LayoutInflater.from(context).inflate(R.layout.qq_copy_dialog_layout, null)

        view.qq.text = serviceQQ.displayText

        val create = AlertDialog.Builder(context)
                .setView(view)
                .create()

        view.dialog_button.setOnClickListener {
            context?.apply {
                create.dismiss()
                copy(serviceQQ.copyText)
                Toaster.message("已复制 qq${if (serviceQQ.type == 0) "群号" else ""} 到剪切板")
            }
        }

        create.show()


    }
}